package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhuizikejithreeig.cn.been.UpDataBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.MainActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.PasswordNameSave;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;

public class SettingActivity extends BasicActivity implements View.OnClickListener {

    private static final int PHOTO_DELAE = 86;
    private LinearLayout mName1;
    private LinearLayout mName3;
    private Button mName8;
    private boolean hasPermission = false;
    private LinearLayout mUpdata;

    private String mPhone;
    private TextView mVersionName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_setting);

        setLeftShow(3, R.mipmap.user);
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //读取内存卡的权限
        hasPermission();
        mName1 = (LinearLayout) findViewById(R.id.name1);
        mName3 = (LinearLayout) findViewById(R.id.name3);
        mUpdata = (LinearLayout) findViewById(R.id.updata);
        mName8 = (Button) findViewById(R.id.name8);
        mVersionName = (TextView) findViewById(R.id.buttontextthree);
        findViewById(R.id.buttontexttwo).setOnClickListener(this);
        findViewById(R.id.buttontextone).setOnClickListener(this);
        mVersionName.setOnClickListener(this);
        mPhone = Utils.getString(ContectUtils.PHONESAVE);

        mName1.setOnClickListener(this);
        mName3.setOnClickListener(this);
        mName8.setOnClickListener(this);

        //版本更新
        mUpdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //无网状态
                if (isConnected()) {
                    checkeSeek();
                } else {
                    ToastMake.showToast(getResources().getString(R.string.string57));
                }
            }
        });
        mVersionName.setText(getVersionName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.name1:
            case R.id.buttontextone:
//                changePhone
                if (TextUtils.isEmpty(mPhone) && !Utils.isPhoneNO(mPhone)) {


                    skipOtherActivity(LoginActivity.class, true);
                    CompontApplayCation.loginNeedFinsh = false;
                    return;
                }
                skipOtherActivity(ChengePhoneActivity.class, false);
                break;
            case R.id.buttontexttwo:
            case R.id.name3:
                if (TextUtils.isEmpty(mPhone) && !Utils.isPhoneNO(mPhone)) {
                    skipOtherActivity(LoginActivity.class, true);
                    CompontApplayCation.loginNeedFinsh = false;
                    return;
                }
                skipOtherActivity(ChengPawActivity.class, false);
                break;
            case R.id.buttontextthree:
                if (isConnected()) {
                    checkeSeek();
                } else {
                    ToastMake.showToast(getResources().getString(R.string.string57));
                }
                break;
            case R.id.name8:

                hasPermission();
                Utils.setString("", ContectUtils.PHONESAVE);
                Utils.setString("", ContectUtils.PASSWORLD);
                Utils.setString("", ContectUtils.STATUS);
                Utils.setString("", ContectUtils.NICKNAME);
                Utils.setString("", ContectUtils.IMAGEICONURI);
                if (hasPermission) {
                    //保存账号跟密码
                    if (Utils.sdIsOk()) {
                        PasswordNameSave.savePassword(SettingActivity.this, "", "", true);
                    }
                    CompontApplayCation.phone = null;
                    //本地sp保存一下

                }
                Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
//                startActivity(new Intent());
                finish();
                break;
        }
    }

    private void hasPermission() {
        PermissionGen.with(SettingActivity.this)
                .addRequestCode(PHOTO_DELAE)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = PHOTO_DELAE)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;

    }

    @PermissionFail(requestCode = PHOTO_DELAE)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(SettingActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

    //先检查版本号
    private void checkeSeek() {

        AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
        builder.setTitle("版本升级提醒");
        builder.setCancelable(false);
        builder.setMessage("已经是最新的版本了");

        builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                        ToastMake.showToast("确定升级");

//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                //TODO:进行升级
//                                downLoadApk(url);
//                            }
//                        }).start();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();


//        int versionCode = getVersionCode();
//        String versionNme = getVersionName();
//        if (versionNme.contains(".")) {
//            String[] vs_name = versionNme.split("\\.");
//
//            for (int i = 0; i < vs_name.length; i++) {
//                if (!vs_name[i].equals("")) {
//                    if (i == 0) {
//                        vs_name1 = Integer.valueOf(vs_name[0]);
//                    }
//                    if (i == 1) {
//                        vs_name2 = Integer.valueOf(vs_name[1]);
//                    }
//                    if (i == 2) {
//                        vs_name3 = Integer.valueOf(vs_name[2]);
//                    }
//                }
//            }
//
//        }
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                OkHttpUtils
//                        .get()
//                        .url(UriContect.VERSION)
//                        .build()
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int id) {
//
//                            }
//
//                            @Override
//                            public void onResponse(String response, int id) {
//                                UpDataBeen dataBeen = GsonUtil.parseJsonToBean(response, UpDataBeen.class);
//                                if (dataBeen == null) {
//                                    return;
//                                }
//                                if (!TextUtils.equals(dataBeen.getStatus(), "1")) {
//
//                                    return;
//                                } else {
//                                    String version = dataBeen.getVersion();
//                                    final String url = dataBeen.getUrl();
//                                    final String title = dataBeen.getTitle();
//                                    final String msg = dataBeen.getMsg();
//                                    if (version.contains(".")) {
//                                        String[] sv_name = version.split("\\.");
//
//                                        for (int i = 0; i < sv_name.length; i++) {
//
//                                            if (!sv_name[i].equals("")) {
//                                                if (i == 0) {
//                                                    sv_name1 = Integer.valueOf(sv_name[0]);
//                                                    System.out.println(sv_name1 + "");
//                                                }
//                                                if (i == 1) {
//                                                    sv_name2 = Integer.valueOf(sv_name[1]);
//                                                    System.out.println(sv_name2 + "");
//                                                }
//                                                if (i == 2) {
//                                                    sv_name3 = Integer.valueOf(sv_name[2]);
//                                                    System.out.println(sv_name3 + "");
//                                                }
//                                            }
//                                        }
//
//                                        runOnUiThread(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                if (vs_name1 > sv_name1) {
//                                                    showDialog(title, msg, url);
//                                                } else {
//
//                                                    if (vs_name2 > sv_name2) {
//                                                        showDialog(title, msg, url);
//                                                    } else {
//
//                                                        if (vs_name3 > sv_name3) {
//                                                            showDialog(title, msg, url);
//                                                        }else {
//                                                            //暂无升级状态
//                                                            showDialog(title, msg, url);
//                                                        }
//
//                                                    }
//                                                }
//                                            }
//                                        });
//
//                                    }
//                                }
//                            }
//                        });
//            }
//        }).start();
    }

    private void showDialog(String title, String message, final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("取消升级");
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("确定升级");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //TODO:进行升级
                        downLoadApk(url);
                    }
                }).start();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void downLoadApk(String url) {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "chezai.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(call.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if (hasPermission) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //判读版本是否在7.0以上
                                //新的启动方法
                                Uri apkUri = FileProvider.getUriForFile(SettingActivity.this, getLocalClassName() + ".fileprovider", response);//在AndroidManifest中的android:authorities值
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                startActivity(install);
                            } else {
                                //以前的启动方法
                                // 通过Intent安装APK文件
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(Uri.fromFile(response.getAbsoluteFile()), "application/vnd.android.package-archive");
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(install);
                            }

                        } else {
                            ToastMake.showToast("请添加读取内存卡权限才能获得最新的版本");
                        }

                    }


                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //TODO:可以自定义进度条
                                //                                ProgressBar progressBar = new ProgressBar(MainActivity.this, null, android.R.attr.progressBarStyleHorizontal);
                                //                                progressBar.setMax(100);
                                //                                progressBar.setProgress(myProgress);

                            }
                        });


                    }
                });

    }

    /**
     * 获取软件版本号
     *
     * @return
     */
    private int getVersionCode() {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = SettingActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    //TODO:进行版本升级操作

    /**
     * 获取版本名字
     *
     * @return
     */
    private String getVersionName() {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = SettingActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }


}
